﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;

namespace weba
{
    public class mk
    {
        public static sjklqDataContext l = new sjklqDataContext();
        private static Regex RegNumber = new Regex("^[0-9]+$");
        public static bool IsNumber(string inputData)
        {
            Match m = RegNumber.Match(inputData);
            return m.Success;
        }
     //   public static UARTEntities l = new UARTEntities();
        public static void Alert(string _Msg)
        {
            string StrScript;
            StrScript = ("<script language=javascript>");
            StrScript += ("alert('" + _Msg + "');");
            StrScript += ("</script>");
            System.Web.HttpContext.Current.Response.Write(StrScript);
        }
        /// <summary>
        /// 警告框
        /// </summary>
        /// <param name="_Msg">警告字串</param>
        /// <param name="_Page">this</param>
        /// <returns>警告框JS</returns>
        public static object Alert(string _Msg, Page _Page)
        {
            string StrScript;
            StrScript = ("<script language=javascript>");
            StrScript += ("alert('" + _Msg + "');");
            StrScript += ("</script>");
            _Page.ClientScript.RegisterStartupScript(_Page.GetType(), "MsgBox", StrScript.ToString());
            return StrScript;
        }
        /// <summary>
        /// 一个含有“确定”，点击以后就转到预设网址的警告框
        /// </summary>
        /// <param name="_Msg">警告字串</param>
        /// <param name="URL">“确定”以后要转到预设网址</param>
        /// <returns>警告框JS</returns>
        public static void Alert(string _Msg, string URL)
        {
            string StrScript;
            StrScript = ("<script language=javascript>");
            StrScript += ("alert('" + _Msg + "');");
            StrScript += ("window.location='" + URL + "';");
            StrScript += ("</script>");
            System.Web.HttpContext.Current.Response.Write(StrScript);
        }
        /// <summary>
        /// 一个含有“确定”，点击以后就转到预设网址的警告框
        /// </summary>
        /// <param name="_Msg">警告字串</param>
        /// <param name="URL">“确定”以后要转到预设网址</param>
        /// <param name="_Page">this</param>
        /// <returns>脚本</returns>
        public static object Alert(string _Msg, string URL, Page _Page)
        {
            string StrScript;
            StrScript = ("<script language=javascript>");
            StrScript += ("alert('" + _Msg + "');");
            StrScript += ("window.location='" + URL + "';");
            StrScript += ("</script>");
            _Page.ClientScript.RegisterStartupScript(_Page.GetType(), "MsgBox2", StrScript.ToString());
            return StrScript;
        }
        public static string InputText(string inputString, int maxLength)
        {
            StringBuilder retVal = new StringBuilder();

            // 检查是否为空
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();

                //检查长度
                if (inputString.Length > maxLength)
                    inputString = inputString.Substring(0, maxLength);

                //替换危险字符
                for (int i = 0; i < inputString.Length; i++)
                {
                    switch (inputString[i])
                    {
                        case '"':
                            retVal.Append("&quot;");
                            break;
                        case '<':
                            retVal.Append("&lt;");
                            break;
                        case '>':
                            retVal.Append("&gt;");
                            break;
                        default:
                            retVal.Append(inputString[i]);
                            break;
                    }
                }
                retVal.Replace("'", " ");// 替换单引号
            }
            return retVal.ToString();

        }
        public static string GetStatusSubmit(int SalesOrderID)
        {
            var bll = l.Sales_NeedMaterialHeader.ToList();
            int SubmitYes = bll.Where(h => h.SalesOrderID == SalesOrderID & h.StatusSubmit == "2").Count();
            int SubmitCount = bll.Where(h => h.SalesOrderID == SalesOrderID).Count();
            if (SubmitCount == 0 || SubmitYes == 0)
            {
                return "1";
            }
            else if (SubmitYes < SubmitCount)
            {
                return "2";
            }
            else if (SubmitYes == SubmitCount)
            {
                return "3";
            }
            else
            {
                return "1";
            }
        }
        public static string GetStatusPurchaseMaterial(int SalesOrderID)
        {
            var bll = l.Sales_NeedMaterialHeader.ToList();
            int PurchaseYes = bll.Where(h => h.SalesOrderID == SalesOrderID & h.StatusPurchaseMaterial == "2" & h.StatusSubmit == "2").Count();
            int PurchaseCount = bll.Where(h => h.SalesOrderID == SalesOrderID & h.StatusSubmit == "2").Count();
            if (PurchaseCount == 0 || PurchaseYes == 0)
            {
                return "1";
            }
            else if (PurchaseYes < PurchaseCount)
            {
                return "2";
            }
            else if (PurchaseYes == PurchaseCount)
            {
                return "3";
            }
            else
            {
                return "1";
            }
        }
        public static void CreatCookies(string cookieName, int time, string strValue, string strDomain)
        {
            HttpCookie aCookie;
            aCookie = new HttpCookie(cookieName);
            aCookie.Value = HttpContext.Current.Server.HtmlEncode(strValue);
            aCookie.Expires = DateTime.Now.AddHours(time);
            if (!string.IsNullOrEmpty(strDomain))
            {
                aCookie.Domain = strDomain;
            }
            HttpContext.Current.Response.Cookies.Add(aCookie);
        }
        public static string GetCookies(string strKey)
        {
            return (HttpContext.Current.Request.Cookies[strKey] != null) ? HttpContext.Current.Request.Cookies[strKey].Value : "";
        }
        public static void CheckState(string strKey, string strThrowUrl, string strMes)
        {
            string strSession = GetSession(strKey);
            if (string.IsNullOrEmpty(strSession))
            {
                System.Web.HttpContext.Current.Response.Write("<script>");
                System.Web.HttpContext.Current.Response.Write("alert(\"" + strMes + "\");");
                System.Web.HttpContext.Current.Response.Write("top.location.href=\"" + strThrowUrl + "\";");
                System.Web.HttpContext.Current.Response.Write("</script>");
                System.Web.HttpContext.Current.Response.End();
            }
        }
        public static string GetSession(string strKey)
        {
            return (HttpContext.Current.Session[strKey] != null) ? HttpContext.Current.Session[strKey].ToString() : "";

        }
        public static string isloged()
        {
            string strSession = GetSession("User_ID");
            if (strSession == GetCookies("User_Name") && strSession != "")
            {
                return strSession + "已登陆";
            }
            else
            {
                return "请登录";
            }
        }
        public static bool islogedtf()
        {
            string strSession = GetSession("User_ID");
            if (strSession == GetCookies("User_Name") && strSession != "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public static void RemoveAllSession()
        {
            HttpContext.Current.Session.RemoveAll();
        }
        public static string UserState(object strValue, object strService)
        {
            string strState = "<font color=green>公用客户</font>";
            switch (strValue.ToString())
            {
                case "0":
                    break;
                case "1":
                    strState = "<font color=red>占用客户</font>[" + strService.ToString().Trim() + "]";
                    break;
                case "2":
                    strState = "成交客户[" + strService.ToString().Trim() + "]";
                    break;
                default:
                    strState = "<font color=#666666>未知状态</font>";
                    break;
            }
            return strState;
        }
        public static decimal GetSubTotal(int PurchaseOrderID)
        {
            return Convert.ToDecimal(mk.l.Sales_PurchaseOrderDetail.Where(y => y.PurchaseOrderID == PurchaseOrderID).Sum(h => h.Subtotal));
        }
        public static bool IsAllArrival(int PurchaseOrderID)
        {
            var b = mk.l.Sales_PurchaseOrderDetail.ToList();
             return   b.Where(y=>y.PurchaseOrderID==PurchaseOrderID).Count()==b.Where(y=>y.PurchaseOrderID==PurchaseOrderID&y.StatusArrival=="1").Count();
        }
       
        public static void StockOut(int MaterialID, decimal Quantity, int LocationID, int RootDepartmentID)
        {
             List<Sales_MaterialInventory> dal = mk.l.Sales_MaterialInventory.ToList();
        
            //先判断库存记录中有无指定材料和仓库的记录，如果有，则更新之
            if ( dal.Where(y=>y.MaterialID==MaterialID&y.LocationID==LocationID).Count()>0)
            {
  Sales_MaterialInventory m = dal.Where(h => h.MaterialID==MaterialID &h.LocationID==LocationID).FirstOrDefault();
                m.Quantity -= Quantity;
                mk.l.SubmitChanges();
            }
            else
            {
                Sales_MaterialInventory m = new  Sales_MaterialInventory();
                m.LocationID =short.Parse( LocationID.ToString()) ;
                m.MaterialID = MaterialID;
                m.Quantity = -Quantity;
                m.RootDepartmentID = RootDepartmentID;
               // dal.Add(m);
                mk.l.Sales_MaterialInventory.InsertOnSubmit(m);
                mk.l.SubmitChanges();
            }
        }
        public static void StockIn(int MaterialID, decimal Quantity, int LocationID, int RootDepartmentID)
        {
            List<Sales_MaterialInventory> dal = mk.l.Sales_MaterialInventory.ToList();
        
            //先判断库存记录中有无指定材料和仓库的记录，如果有，则更新之，如果没有，则添加之
            if (dal.Where(y => y.MaterialID == MaterialID & y.LocationID == LocationID).Count() > 0)
            {
                Sales_MaterialInventory m = dal.Where(h => h.MaterialID == MaterialID & h.LocationID == LocationID).FirstOrDefault();
                m.Quantity += Quantity;
               // dal.Update(m);
                mk.l.SubmitChanges();
            }
            else
            {
                Sales_MaterialInventory m = new Sales_MaterialInventory();
                m.LocationID = short.Parse(LocationID.ToString());
                m.MaterialID = MaterialID;
                m.Quantity = Quantity;
                m.RootDepartmentID = RootDepartmentID;
                //dal.Add(m);
                mk.l.Sales_MaterialInventory.InsertOnSubmit(m);
                mk.l.SubmitChanges();
            }
        }
        private static string GenerateCheckCode()
        {
            int number;
            char code;
            string checkCode = String.Empty;

            System.Random random = new Random();

            for (int i = 0; i < 5; i++)
            {
                number = random.Next();

                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('A' + (char)(number % 26));

                checkCode += code.ToString();
            }
            //将生成的验证码加入Session中
            HttpContext.Current.Session.Add("CheckCode", checkCode.ToLower());
            return checkCode;
        }

        private static void CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == String.Empty)
                return;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                Random random = new Random();

                //清空图片背景色
                g.Clear(Color.White);

                //画图片的背景噪音线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);

                //画图片的前景噪音点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ContentType = "image/Gif";
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Redirect("ErrorMessage.aspx@Error=" + ex);
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }

        public static void CreateCheckCodeImage()
        {
            CreateCheckCodeImage(GenerateCheckCode());
        }
    }
}